<template>
    <div class="goods-list">
      <div class="goods-item" v-for="item in goodslist" :key="item.id">
        <!-- 修改为 router-link -->
        <router-link :to="{ name: 'goods_info', params: { id: item.id } }">
          <img :src="item.image" alt="商品图片">
          <h1 class="title">{{ item.name }}</h1>
          <p class="info">
            <span class="price">¥{{ item.price }}</span>
            <span class="sell">剩余 {{ item.num }} 件</span>
          </p>
        </router-link>
      </div>
      <!-- 加载更多按钮 -->
      <mt-button class="more" v-if="goodslist.length !== 0" size="large" @click="getMore">加载更多</mt-button>
    </div>
  </template>
  
  <script>
  export default {
    props: ['category_id'],
    data() {
      return {
        goodslist: [], // 存放商品列表数据
        last_id: 0,    // 记录最后一条商品的 ID
      };
    },
    created() {
      this.getGoodsList();
    },
    methods: {
      getGoodsList() {
        // 打开加载指示器
        this.$indicator.open({
          text: '加载中'
        });
  
        // 设置请求参数
        let params = {
          last_id: this.last_id,       // 传递 last_id
          category_id: this.category_id
        };
  
        // 发起请求
        this.$http.get('goodslist', { params: params }).then(res => {
          // 关闭加载指示器
          this.$indicator.close();
  
          // 处理返回的数据
          if (res.data.code === 1) {
            if (res.data.data.length > 0) {
              // 追加数据
              this.goodslist = this.goodslist.concat(res.data.data);
              // 更新 last_id
              this.last_id = res.data.data[res.data.data.length - 1].id;
            } else if (this.goodslist.length > 0) {
              this.$toast('已经到达底部'); // 显示提示信息
            } else {
              this.$toast('列表为空'); // 显示提示信息
            }
          }
        }).catch(error => {
          // 关闭加载指示器
          this.$indicator.close();
  
          // 处理请求错误
          window.console.error('请求商品列表失败:', error);
        });
      },
      // 加载更多
      getMore() {
        this.getGoodsList();
      }
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .goods-list {
    display: flex;
    flex-wrap: wrap;
    padding-left: 10px;
  
    .goods-item {
      width: calc(calc(100% / 2) - 10px);
      margin: 10px 10px 0 0;
      background: #fff;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      border-radius: 10px;
      padding: 10px;
  
      img {
        width: 100%;
      }
  
      .title {
        font-size: 14px;
        color: #333;
        margin: 10px 0;
      }
  
      .info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 0;
  
        .price {
          color: red;
          font-weight: bold;
          font-size: 16px;
        }
  
        .sell {
          font-size: 13px;
        }
      }
    }
  
    .more {
      margin: 15px 0;
      font-size: 14px;
    }
  }
  </style>